#include "prj1u.h"
#include "common_typedef.h"
#include "Heartbeat.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdint.h>
#include "SysCall.h"
#include "GuiFrontPanel.h"

static int g_fdBuz = -1;
static int g_ethLinkStaHis = -123;
static devSta g_ethLinkState = DEVSTA_ETH_OFFLINE;

devSta GetEthLinkState();
void BuzEventOut(EventTypeID evt);

int HeartBeatMain(void)
{
    printf("[%s] enter\n", APP_HEARTBEAT);
    while (1)
    {
        usleep(1000 * 50);
        devSta ethLinkSta = GetEthLinkState();
        LogStateBar("#00ff00 %s# | delay: %s", ethLinkSta == DEVSTA_ETH_ONLINE ? GetEthIP() : "LINK_DOWN", GetEthDelayMicrosec());
        if (ethLinkSta == g_ethLinkStaHis) {
            continue;
        }
        printf("[%s] eth link state [%d] -> [%d]\n", APP_HEARTBEAT, g_ethLinkStaHis, ethLinkSta);
        g_ethLinkStaHis = ethLinkSta;
        BuzEventOut(ethLinkSta == DEVSTA_ETH_ONLINE ? EVTID_ETH_LINKUP : EVTID_ETH_LINKDOWN);
    }

    return 0;
}

void HeartBeatExit(void)
{
    printf("[%s] exit\n", APP_HEARTBEAT);
    close(g_fdBuz);
}

void BuzEventOut(EventTypeID evt)
{
    g_fdBuz = open(DEV_MAINBD_BUZ, O_RDWR);
    if (g_fdBuz < 0) {
        return;
    }
    int buzSequence[][4] = {
        {50, 10, 200, 10},
        {200, 10, 50, 10},
    };
    if (evt >= sizeof(buzSequence) / sizeof(buzSequence[0])) {
        return;
    }
    int* pSequence = buzSequence[evt];
    uint8_t command = 1;
    for (int idx = 0; idx < 2; idx++) {
        command = 1;
        write(g_fdBuz, &command, sizeof(command));
        usleep(1000 * pSequence[idx * 2]);
        command = 0;
        write(g_fdBuz, &command, sizeof(command));
        usleep(1000 * pSequence[idx * 2 + 1]);
    }

    close(g_fdBuz);
    g_fdBuz = -1;
}